package com.bby.disk.aop;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bby.common.aop.ParseToken;
import com.bby.common.utils.R;
import com.bby.common.utils.StatusCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
@Aspect
public class LoginCheckAop {
    private final JedisPool jedisPool;
    Logger logger = LoggerFactory.getLogger(this.getClass());
    public LoginCheckAop(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Pointcut("within(com.bby.disk.controller.*) && @annotation(com.bby.common.aop.ParseToken)")
    public void pointCut(){}

    @Around("pointCut() && @annotation(parseToken)")
    public Object parseTokenAround(ProceedingJoinPoint pjp, ParseToken parseToken) throws Throwable {
        Object[] args = pjp.getArgs();
        ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (attributes == null){
            return  pjp.proceed(args);
        }
        String token = attributes.getRequest().getHeader("token");
        logger.debug("{} => token={}",pjp.getSignature().getName(),token);
        if (ObjectUtil.isEmpty(token)){
            logger.debug("参数：{}", ArrayUtil.toString(args));
            return pjp.proceed(args);
        }
        try(Jedis jedis = jedisPool.getResource()){
            jedis.select(2);
            String userId = jedis.get(token);
            args[0] = userId;
            logger.debug("参数：{}", ArrayUtil.toString(args));
        }catch (Exception ignored){}
        if (parseToken.require() && ObjectUtil.isEmpty(args[0])){
            return R.error(StatusCode.NOT_LOGIN,"抱歉，您没有登录！");
        }
        return pjp.proceed(args);
    }
}
